<script setup>
import List from '../components/List.vue';
import ClusterNamespaceSelector from '../components/ClusterNamespaceSelector.vue'
import { getDeploymentListHandler as getListHandler, deleteDeploymentHandler as deleteHandler ,updateDeploymentHandler as updateHandler } from '../../api/deployment.js';
import {reactive, computed, ref, toRefs} from 'vue'
import GenericOptions from '../components/GenericOptions.vue'
import { ElMessage,ElMessageBox  } from 'element-plus'
// import CodeMirror  from '../components/CodeMirror.vue'
import DialogYaml from '../components/DialogYaml.vue';
import { obj2Yaml } from '../../utils/utils';
import { useRouter } from 'vue-router';
const router = useRouter()
const data = reactive({
  items: [],
  clusterId: "",
  namespace: "",
  yamlContent: ""
})
// 定义一个查询Pod列表的函数
const getList = () => {
  getListHandler(data.clusterId, data.namespace).then(
    (res) => {
      data.items = res.data.data.items
      console.log("items:",data.items)
    }
  )
}
// 回调函数
const rollback = (clusterId, namespace)=> {
  data.clusterId = clusterId
  data.namespace = namespace
  getList()
}
const search = ref('')
const filterTableData = computed(() => {
  if (!data.items) return [] // 如果 items 不存在，返回空数组
  return data.items.filter(item => 
    !search.value ||
    item.metadata?.name?.toLowerCase().includes(search.value.toLowerCase())
  )
})

// 判断pod的重启次数和容器状态
const getPodRestartCount = computed(() => (row) => {
  // console.log("row:", row)
  let restartCount = 0
  let readyCount = 0
  row.status.containerStatuses.forEach(item => {
    restartCount += item.restartCount
    if (item.ready){
      // 表明当前容器已经启动完成
      readyCount += 1
    }
  })
  // 获取当前Pod一共有多少个容器
  const containerTotal = row.status.containerStatuses.length
  // 1/2 2/2
  const readyStatus = `${readyCount}/${containerTotal}`
  return [restartCount, readyStatus]
})
// 展示详情
const showDetail = ref(false)
const detail = (row) => {
  const item = JSON.parse(JSON.stringify(row))
  // 删除managedFields
  delete item.metadata.managedFields
  // 把apiVersion kind补上去
  const itemtemp = {
    "apiVersion": "apps/v1",
    "kind": "Deployment",
    "metadata": item.metadata,
    "spec": item.spec
  }
  // 把当前数据转成yaml
  const yamlData = obj2Yaml(itemtemp)
  data.yamlContent = yamlData
  showDetail.value = true
}
const {yamlContent,clusterId} = toRefs(data)
const changeReplicas = (newValue,oldValue,row,resourceType) => {
  console.log(newValue,oldValue)
  //1.拿到新副本
  //2.更新配置
  //3.row的副本数改为之前的值
  console.log("当前配置:",row.spec.replicas)
  ElMessageBox.confirm(
    `确定要更改${resourceType}:${row.metadata.name}的副本数为:${newValue}吗?`, 
    '提示', 
    {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  .then(async() => {
    //点击确定要执行的指令
    const postData = {
      clusterId: data.clusterId,
      namespace: data.namespace,
      item: row
    }
   await updateHandler(postData).then((res)=>{
    ElMessage.success(res.data.message)
    }).catch((res)=>{
      row.spec.replicas = oldValue
      ElMessage.warning(res.data.message)
    })
    }).catch(()=>{
      //点击取消执行的指令
      row.spec.replicas = oldValue
    })
}
const updatePaused = async(row) => {
    console.log("当前的值:",row.spec.paused)
    //如果true: 关闭暂停更新
    //如果false：打开暂停更新
    //更新节点的状态
    const postData = {
        clusterId: data.clusterId,
        namespace: data.namespace,
        item: row
      }
       await updateHandler(postData)
       .then((res) => {
           if (res.data.status == 200){
            ElMessage.success(res.data.message)
           }else {
            ElMessage.error(res.data.message)
            row.spec.paused = !row.spec.paused
          }
        }).catch(() => {
            err =>{
              row.spec.paused = !row.spec.paused
            }
        })
}
</script>

<template>
  <List title="Deployment列表">
    <template #header-options>
      <ClusterNamespaceSelector @namespaceChangedRollback="rollback">

      </ClusterNamespaceSelector>
      <el-input v-model="search" size="small" placeholder="搜索" style="width: 140px; margin-left: 10px; height: 32px;" />
    </template>
    <template #main>
      <el-table
      border 
      height="480" 
      :data="filterTableData" 
      style="width: 100%"
      :default-sort="{prop: 'metadata.creationTimestamp', order: 'descending'}"
      >
        <el-table-column fixed prop="" align="center" label="名称" width="200px">
          <template #default="scope">
            <el-button link type="primary"  @click="detail(scope.row)">{{ scope.row.metadata.name }}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="metadata.creationTimestamp" align="center" label="创建时间" width="240" sortable />
        <el-table-column prop="" align="center" label="副本" width="180">
          <template #default="scope">
            <el-input-number 
            v-model="scope.row.spec.replicas" 
            :min="0" 
            :max="100" 
            :controls="false" 
            @change="(currentValue,oldValue) =>changeReplicas(currentValue,oldValue,scope.row,'Deployment')"
            placeholder="请输入副本数" />
          </template>
        </el-table-column>
        <el-table-column prop="" align="center" label="状态" width="120" sortable>
          <template #default="scope">
            <span title="成功启动的副本/总副本" v-if="scope.row.spec.replicas  != 0" >{{ scope.row.status.readyReplicas }}/{{ scope.row.status.replicas }}</span>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column prop="" align="center" label="暂停更新" width="180">
          <template #default="scope">
            <el-switch v-model="scope.row.spec.paused" @change="updatePaused(scope.row)"/>
          </template>
        </el-table-column>
        <el-table-column prop="metadata.namespace" align="center" label="命名空间" width="240" />
        <el-table-column fixed="right" align="center" label="操作" width="320" >
          <template #default="scope">
            <GenericOptions
            v-on:delete-rollback="getList"
            :name="scope.row.metadata.name"
            :cluster-id="clusterId"
            :disabled ="scope.row.metadata.deletionTimestamp" 
            resource-type="Deployment"
            :namespace="scope.row.metadata.namespace"
            :show-schedule-options="true"
            :item="scope.row"
            >
            </GenericOptions>
          </template>
        </el-table-column>
      </el-table>
    </template>
  </List>
  <DialogYaml
  :cluster-id="data.clusterId"
  :namespace="data.namespace"
  :yaml-content="yamlContent"
  :show-dialog="showDetail"
  @close-dialog-handler="(val)=>{showDetail = val}"
  >

  </DialogYaml>
  <!-- <el-dialog
  v-model="showDetail" 
  width="70%">
  <template #header="{ titleId, titleClass }">
    <div class="my-header">
      <div :id="titleId" :class="titleClass" style="margin: 10px auto 0 auto;">
        <el-button type="primary" title="资源所在的集群" >
          <i class="iconfont icon-kubernetes" style="font-size: 20px;" />
          <span style="font-size: 20px;margin-left: 10px;">{{ data.clusterId }}</span>
        </el-button>
        <el-button type="primary" title="资源所在的命名空间" >
          <i class="iconfont icon-Namespace" style="font-size: 20px;" />
          <span style="font-size: 20px;margin-left: 10px;">{{ data.namespace }}</span>
        </el-button>
      </div>
    </div>
  </template>
    <CodeMirror
    v-model="yamlContent"
    ></CodeMirror>
  </el-dialog> -->
</template>

<style scoped>
.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
</style>
